<template>
    <div class="page">
      <h2>登录</h2>
      <form @submit.prevent="handleLogin">
        <div class="input-group">
          <label for="username">账号:</label>
          <input
            type="text"
            id="username"
            v-model="username"
            placeholder="请输入账号"
            required
          />
        </div>
        <div class="input-group">
          <label for="password">密码:</label>
          <input
            type="password"
            id="password"
            v-model="password"
            placeholder="请输入密码"
            title="请输入密码"
            required
          />
        </div>
        <div class="role-selection">
          <label>
            <input type="radio" name="role" value="student" v-model="role" />
            学员
          </label>
          <label>
            <input type="radio" name="role" value="admin" v-model="role" />
            管理员
          </label>
        </div>
        <button type="submit" class="login-button">登录</button>
      </form>
      <div class="links">
        <a href="#" @click.prevent="$emit('toggleForm', 'register')">注册账号</a>
        <a href="#" @click.prevent="$emit('toggleForm', 'forgotPassword')">忘记密码?</a>
      </div>
    </div>
  </template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { loginApi } from '../api/user';

const router = useRouter();
const username = ref('');
const password = ref('');
const role = ref('student');

const handleLogin = async () => {
  try {
    let res = await loginApi({
      username: username.value,
      password: password.value,
      role: role.value
    });
    if(res.code === 200) {
      localStorage.setItem('userRole', role.value);
      router.push(role.value === 'student' ? '/main' : '/administrater');
    }
  } catch (error) {
    console.error('登录错误:', error);
  }
};
</script>
  
  <!-- <script>
  import { useRouter } from 'vue-router';
  import {loginApi} from '../api/user';
  const router = useRouter();
  export default {
    data() {
      return {
        username: '',
        password: '',
        role: 'student',
      };
    },
    methods: {
      async handleLogin() {
        // 处理登录逻辑
        let res = await loginApi({account: this.username, password: this.password,role: this.role});
        if(res.data.code==200){
          router.push({path: '/dashboard'});
        }else{
          this.$message.error(res.data.message || '登录失败，请检查用户名和密码');
        }
      },
    },
  };
  </script> -->